﻿using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using StartupToolsetInterfaces;

namespace MyCompany.StartupToolsetRefactored
{
  [PackageRegistration(UseManagedResourcesOnly = true)]
  [DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0")]
  [InstalledProductRegistration(false, "#110", "#112", "1.0", IconResourceID = 400)]
  [ProvideLoadKey("Standard", "1.0", "StartupToolsetRefactored", "MyCompany", 1)]
  [ProvideMenuResource(1000, 1)]
  [ProvideToolWindow(typeof(CalculationToolWindow))]
  [ProvideService(typeof(SCalculationService))]
  [Guid(GuidList.guidStartupToolsetRefactoredPkgString)]
  public sealed class StartupToolsetRefactoredPackage : Package
  {
    public StartupToolsetRefactoredPackage()
    {
      IServiceContainer serviceContainer = this;
      ServiceCreatorCallback creationCallback = CreateService;
      serviceContainer.AddService(typeof(SCalculationService), creationCallback, true);
    }

    protected override void Initialize()
    {
      Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
      base.Initialize();

      OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
      if (null != mcs)
      {
        CommandID menuCommandID = new CommandID(GuidList.guidStartupToolsetRefactoredCmdSet, (int)PkgCmdIDList.cmdidCalculateTool);
        MenuCommand menuItem = new MenuCommand(ShowCalculateToolCallback, menuCommandID);
        mcs.AddCommand(menuItem);
      }
    }

    private void ShowCalculateToolCallback(object sender, EventArgs e)
    {
      ToolWindowPane window = FindToolWindow(typeof(CalculationToolWindow), 0, true);
      if ((null == window) || (null == window.Frame))
      {
        throw new NotSupportedException(Resources.CanNotCreateWindow);
      }
      IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
      Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
    }

    private object CreateService(IServiceContainer container, Type serviceType)
    {
      if (container != this)
      {
        return null;
      }
      if (typeof(SCalculationService) == serviceType)
      {
        return new CalculationService();
      }
      return null;
    }
  }
}